package com.test.javafaq_portal.security;


import com.test.javafaq_portal.service.impl.UserDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)//开启Security权限功能
public class SercurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired(required = false)
    UserDetailsServiceImpl userDetailsService;

    //配置登陆验证
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
    }


    //设置springsecurity授权范围和登陆页面
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()//关闭跨域攻击
                .authorizeRequests()//开始设置授权范围
                .antMatchers(
                        "/img/*",
                        "/js/*",
                        "/css/*",
                        "/bower_components/**",
                        "/login.html",
                        "/register.html",
                        "/register"
                ).permitAll()  //上面的路径允许直接访问
                .anyRequest().authenticated() // 其他资源需要登陆
                .and().formLogin()//登陆方式是表单
                .loginPage("/login.html") //指定登陆页
                .loginProcessingUrl("/login") //当登录页提交时，会提交给哪个路径
                .failureForwardUrl("/login.html?error")//登录失败提示
                .defaultSuccessUrl("/index.html")//登陆成功跳转到 index.html
                .and().logout()  //配置登出
                .logoutUrl("/logout") //设置等处路径
                .logoutSuccessUrl("/login.html?logout");//登出成功跳转到登录页，并提示
    }


    //想spring容器中加入一个加密对象
//    @Bean
//    public PasswordEncoder passwordEncoder(){
//        return new BCryptPasswordEncoder();
//    }
}
